Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

130
Views
Multiple updates on a single field causes "Updating the path 'X' would create a conflict at 'X'" in mongoDB

I have the following update operation:

private async onCategoryImagesModified(data: ModifiedFilesEventData) {
        this.categoryModel
            .findByIdAndUpdate(data.resourceId, {
                $pullAll: { images: data.removedFiles || [] },
                $addToSet: { images: { $each: data.addedFiles || [] } }
            }).catch(error => this.logger.warn(error))
}

Basically, every time images of model category changes I want to update the document by removing all the removed paths from images and adding the new paths to images.

I get that I can't reference the same field more than once inside an update, but is there a way to do this without 2 separate update operations?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

I get that I can't reference the same field more than once inside an update

The update will not support the same field more than once, if you want to do this in the single query you can try update with aggregation pipeline starting from MongoDB 4.2,

  • $filter to iterate loop of images and remove the input elements by $not and $in
  • $setUnion to get unique elements from input elements and images field
private async onCategoryImagesModified(data: ModifiedFilesEventData) {
  let stages = [];
  // remove fields
  if (data.removedFiles) {
    stages.push({
      $set: {
        images: {
          $filter: {
            input: "$images",
            cond: { $not: { $in: ["$$this", data.removedFiles] } }
          }
        }
      }
    });
  }

  // add fields
  if (data.addedFiles) {
    stages.push({
      $set: { images: { $setUnion: ["$images", data.addedFiles] } }
    });
  }

  this.categoryModel
    .findByIdAndUpdate(data.resourceId, [stages])
    .catch(error => this.logger.warn(error))
}

Playground

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!